package net.sf.calibur.transport;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Map;
import java.util.WeakHashMap;

import javax.crypto.CipherInputStream;

public class CipherFactory {
	static class SingletonHolder {
		static CipherFactory instance = new CipherFactory();
	}

	public static CipherFactory getInstance() {
		return SingletonHolder.instance;
	}

	private MessageDigest shaDigest;
	private Map<Session, CipherContext> allContexts;

	private CipherFactory() {
		try {
			/*
			 * 添加新安全算法,如果用JCE就要把它添加进去。 
			 * java中调用sun公司提供的3DES加密解密算法时 ，需要使
			 * 用到$JAVA_HOME/jre/lib/目录下如下的4个jar包： jce.jar
			 * security/US_export_policy.jar security/local_policy.jar
			 * ext/sunjce_provider.jar
			 */

			Security.addProvider(new com.sun.crypto.provider.SunJCE());
			shaDigest = MessageDigest.getInstance("SHA");
			CipherContext.initKey();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}

		allContexts = new WeakHashMap<Session, CipherContext>();
	}

	private synchronized CipherContext getContext(Session session) {
		CipherContext ctx = allContexts.get(session);
		if (ctx == null) {
			ctx = new CipherContext(session, shaDigest);
			allContexts.put(session, ctx);
		}

		return ctx;
	}

	public CipherInputStream getCipherInputStream(Session session,
			InputStream src) throws Exception {
		CipherContext ctx = getContext(session);
		return ctx.getCipherInputStream(session, src);
	}
}
